package com.example.stlink.activitys.fragmentChild.activityTeaHome;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.example.stlink.R;
import com.example.stlink.activitys.MapActivity;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.request.CourseCreateSignRequest;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.utils.CommonUtils;
import com.example.stlink.utils.QRCodeUtil;
import com.example.stlink.utils.httpUtils.PostBodyParamHttpUtils;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.timepicker.MaterialTimePicker;
import com.google.android.material.timepicker.TimeFormat;

import java.text.ParseException;
import java.util.Objects;

public class CreateSign extends AppCompatActivity {

    private ImageView abIvTitle;
    private TextView tvCourseName;
    private TextInputEditText etStuAmount;
    private TextInputEditText etStartTime;
    private TextInputEditText etEndTime;
    private TextInputEditText etLocation;
    private TextInputEditText etCode;
    private ImageView ivAddImg;
    private AppCompatButton abBtSave;

    private int currYear;
    private int currMonth;
    private int currDay;
    private int currHour;
    private int currMin;
    private int currSecond;

    private Long startTimeStamp;
    private Long endTimeStamp;
    private String courseName;

    private boolean hasChooseStartTime;
    private boolean hasChooseEndTime;

    private MaterialTimePicker startTimePicker;
    private MaterialTimePicker endTimePicker;
    private Bundle bundle;
    private Handler handler;

    private static ActivityResultLauncher<Intent> intentActivityResultLauncher;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tea_create_sign);

        initView();
    }

    /**
     * 绑定控件
     */
    private void initView(){

        CommonUtils.changeStatusBar(CreateSign.this);

        hasChooseStartTime = false;
        hasChooseEndTime = false;
        abIvTitle = findViewById(R.id.ab_iv_title);
        tvCourseName = findViewById(R.id.tv_course_name);
        etStuAmount = findViewById(R.id.et_stu_amount);
        etStartTime = findViewById(R.id.et_start_time);
        etEndTime = findViewById(R.id.et_end_time);
        etLocation = findViewById(R.id.et_location);
        etCode = findViewById(R.id.et_code);
        ivAddImg = findViewById(R.id.iv_add_img);
        abBtSave = findViewById(R.id.ab_bt_save);

        //禁止输入
        etStartTime.setKeyListener(null);
        etEndTime.setKeyListener(null);
        etLocation.setKeyListener(null);

        bundle = getIntent().getExtras();
        courseName = bundle.getString(ModelFieldConstants.COURSE_NAME);
        if(!TextUtils.isEmpty(courseName)){
            tvCourseName.setText(courseName);
        }


        Long curTimeStamp = System.currentTimeMillis();

        String currTime = CommonUtils.stampToDate(String.valueOf(curTimeStamp), "yyyy-MM-dd-HH-mm-ss");
        String[] timeStrs = currTime.split("-");
        currYear = Integer.parseInt(timeStrs[0]);
        currMonth = Integer.parseInt(timeStrs[1]);
        currDay = Integer.parseInt(timeStrs[2]);
        currHour = Integer.parseInt(timeStrs[3]);
        currMin = Integer.parseInt(timeStrs[4]);
        currSecond = Integer.parseInt(timeStrs[5]);

        startTimePicker = new MaterialTimePicker.Builder()
                .setTimeFormat(TimeFormat.CLOCK_24H)
                .setHour(currHour)
                .setMinute(currMin)
                .setTitleText("开始时间选择")
                .setPositiveButtonText("确认")
                .setNegativeButtonText("取消")
                .build();
        endTimePicker = new MaterialTimePicker.Builder()
                .setTimeFormat(TimeFormat.CLOCK_24H)
                .setHour(currHour)
                .setMinute(currMin)
                .setTitleText("结束时间选择")
                .setPositiveButtonText("确认")
                .setNegativeButtonText("取消")
                .build();

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            System.out.println("registerForActivityResult...........................");
            if (resultCode == 100) {
                assert data != null;
                getIntent().putExtras(data.getExtras());
                String latLon = getIntent().getExtras().getString(ModelFieldConstants.LOCATION);
                if(!TextUtils.isEmpty(latLon)){
                    etLocation.setText(latLon);
                }
            }else if(resultCode == 200){
                assert data != null;
                getIntent().putExtras(data.getExtras());
                bundle = getIntent().getExtras();
                courseName = bundle.getString(ModelFieldConstants.COURSE_NAME);
                if(courseName != null){
                    tvCourseName.setText(courseName);
                }
            }
        });

        setClickListener();
    }

    /**
     * 设置点击事件
     */
    private void setClickListener(){
        tvCourseName.setOnClickListener(v -> {
            Intent intent = new Intent(CreateSign.this, ChooseCourse.class);
            intent.putExtras(getIntent().getExtras());
            intentActivityResultLauncher.launch(intent);
        });
        abIvTitle.setOnClickListener(v -> finish());
        //点击添加图片
        ivAddImg.setOnClickListener(v -> {
            String signCode = Objects.requireNonNull(etCode.getText()).toString();
            if (TextUtils.isEmpty(signCode)){
                Toast.makeText(CreateSign.this, "请先输入签到码", Toast.LENGTH_SHORT).show();
            }else{
                Bitmap codeBitmap = QRCodeUtil.createQRCode(signCode,500,500,null);
                ivAddImg.setImageBitmap(codeBitmap);
            }
        });
        //设置回调方法，进行获取选择的时间，并将其刷新到界面
        startTimePicker.addOnPositiveButtonClickListener(v -> {
            int startHour = startTimePicker.getHour();
            int startMin = startTimePicker.getMinute();
            String startTime = currYear + "-" +
                    currMonth + "-" +
                    currDay + " " +
                    startHour + ":" +
                    startMin + ":" + "00";
            try {
                startTimeStamp = Long.parseLong(CommonUtils.dateToStamp(startTime, "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            etStartTime.setText(startTime);
            hasChooseStartTime = true;
        });
        endTimePicker.addOnPositiveButtonClickListener(v -> {
            int endHour = endTimePicker.getHour();
            int endMin = endTimePicker.getMinute();
            String endTime = currYear + "-" +
                    currMonth + "-" +
                    currDay + " " +
                    endHour + ":" +
                    endMin + ":" + "00";
            try {
                endTimeStamp = Long.parseLong(CommonUtils.dateToStamp(endTime, "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            etEndTime.setText(endTime);
            hasChooseEndTime = true;
        });
        //课程开始时间
        etStartTime.setOnClickListener(v -> {
            if(!startTimePicker.isAdded()){
                startTimePicker.show(getSupportFragmentManager(), "Hello");
            }
        });
        //课程结束时间
        etEndTime.setOnClickListener(v -> {
            if(!endTimePicker.isAdded()){
                endTimePicker.show(getSupportFragmentManager(), "Hello");
            }
        });
        //定位
        etLocation.setOnClickListener(v -> {

            LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
            boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
            if (ok) {//开了定位服务
                if (ContextCompat.checkSelfPermission(CreateSign.this, Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) { //有权限
                    Intent intent = new Intent(CreateSign.this, MapActivity.class);
                    intent.putExtras(getIntent().getExtras());
                    intentActivityResultLauncher.launch(intent);
                } else {    // 跳转到授予定位权限界面
                    Toast.makeText(CreateSign.this, "需要授予定位权限", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + this.getPackageName()));
                    startActivity(intent);
                }
            } else {
                Toast.makeText(CreateSign.this, "系统检测到未开启GPS定位服务", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
        //保存按钮
        abBtSave.setOnClickListener(v -> {
            bundle = getIntent().getExtras();
            String courseName =  bundle.getString(ModelFieldConstants.COURSE_NAME);
            String stuAmountStr = Objects.requireNonNull(etStuAmount.getText()).toString();
            String location = Objects.requireNonNull(etLocation.getText()).toString();
            String signCodeStr = Objects.requireNonNull(etCode.getText()).toString();
            long courseId = bundle.getLong(ModelFieldConstants.COURSE_ID);
            Long userId = bundle.getLong(ModelFieldConstants.ID);
            if(!TextUtils.isEmpty(courseName)){
                if(!TextUtils.isEmpty(stuAmountStr)){
                    if(hasChooseStartTime && hasChooseEndTime){
                        if(startTimeStamp <= endTimeStamp){
                            if(!TextUtils.isEmpty(location)){
                                if(!TextUtils.isEmpty(signCodeStr)){
                                    try{
                                        Long stuAmount = Long.parseLong(stuAmountStr);
                                        try{
                                            Long signCode = Long.parseLong(signCodeStr);
                                            CourseCreateSignRequest courseCreateSignRequest = new CourseCreateSignRequest();
                                            courseCreateSignRequest.setCourseName(courseName);
                                            courseCreateSignRequest.setTotal(stuAmount);
                                            courseCreateSignRequest.setBeginTime(startTimeStamp);
                                            courseCreateSignRequest.setEndTime(endTimeStamp);
                                            courseCreateSignRequest.setCourseAddr(location);
                                            courseCreateSignRequest.setCourseId(courseId);
                                            courseCreateSignRequest.setUserId(userId);
                                            courseCreateSignRequest.setSignCode(signCode);
                                            handler = new Handler(msg -> {
                                                if(msg.arg1 == 200){
                                                    String error = (String) msg.obj;
                                                    Toast.makeText(CreateSign.this, error, Toast.LENGTH_SHORT).show();
                                                }else if(msg.arg1 == 100){
                                                    Toast.makeText(CreateSign.this, "创建签到成功", Toast.LENGTH_SHORT).show();
                                                    //创建成功后直接结束当前活动，并且跳到查看签到状态
                                                    Intent intent = new Intent();
                                                    bundle = getIntent().getExtras();
                                                    bundle.putLong(ModelFieldConstants.NOW_SIGN_COURSE_ID, courseId);
                                                    bundle.putString(ModelFieldConstants.NOW_SIGN_COURSE_NAME, courseName);
                                                    bundle.putSerializable(ModelFieldConstants.COURSE_CREATE_SIGN_REQUEST , courseCreateSignRequest);
                                                    intent.putExtras(bundle);
                                                    setResult(100,intent);
                                                    finish();
                                                }
                                                return false;
                                            });
                                            createSign(courseCreateSignRequest);
                                        }catch (NumberFormatException numberFormatException){
                                            Toast.makeText(CreateSign.this, "请输入数字作为签到码", Toast.LENGTH_SHORT).show();
                                        }
                                    }catch (NumberFormatException numberFormatException){
                                        Toast.makeText(CreateSign.this, "请输入正确的签到人数", Toast.LENGTH_SHORT).show();
                                    }
                                }else{
                                    Toast.makeText(CreateSign.this, "请先输入签到口令", Toast.LENGTH_SHORT).show();
                                }
                            }else{
                                Toast.makeText(CreateSign.this, "请先选择签到地点", Toast.LENGTH_SHORT).show();
                            }
                        }else{
                            Toast.makeText(CreateSign.this, "时间设置错误", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(CreateSign.this, "请先选择开始结束时间", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(CreateSign.this, "请先输入待签到人数", Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(CreateSign.this, "请先选择课程", Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 创建签到
     * @param courseCreateSignRequest 封装好的请求类
     */
    private void createSign(CourseCreateSignRequest courseCreateSignRequest){
        new Thread(() -> {
            System.out.println( "courseCreateSignRequest : " + courseCreateSignRequest.toString() + "..............................");
            String json = JSON.toJSONString(courseCreateSignRequest);
            String url = UrlConstants.TEACHER_INITIATE;

            new PostBodyParamHttpUtils() {
                @Override
                public void nextMethod(BaseResponse<Object> baseResponse) {
                    Message message = new Message();
                    message.arg1 = 100;
                    handler.sendMessage(message);
                }
                @Override
                public void failedMethod(BaseResponse<Object> baseResponse) {
                    Message message = new Message();
                    message.arg1 = 200;
                    message.obj = baseResponse.getMsg();
                    handler.sendMessage(message);
                }
            }.postConnect(url, json);
        }).start();
    }
}
